<?php

namespace app\common\business;

use catcher\exceptions\FailedException;
use catcher\wxpush\src\Mediway\Auth;
use catcher\wxpush\src\Mediway\SignGenerator;
use catcher\wxpush\src\Mediway\AESDataMcrypt;
use catcher\wxpush\src\Mediway\GatewayManager;
use think\facade\Log;

class WechatPush
{
    protected string $url = 'http://10.10.1.61:8088/wx_push_api/';
    protected string $appId = 'cf71cc3c-65c0-8f82-53f3-7a5313f6b27a';
    protected string $appKey = 'f5989ecdf14a70e52910cb596fe87ec5';

    public function __construct()
    {

    }

    /**
     * 获取access_token
     * @return array
     */
    private function getToken(): array
    {
        $auth = new Auth($this->url, $this->appId, $this->appKey);
        $res = $auth->getToken();
        list($code, $duration, $header, $body, $error) = $res;
        Log::write("微信推送返回：" . json_encode($res), 'info');
        return json_decode($body, true);
    }

    /**
     * 微信推送
     * @param int $type 1 随访，2 宣教
     * @param string $patientId 患者id
     * @param string $locDesc 推送科室
     * @param string $admDate 推送时间
     * @param string $note 推送内容
     * @param string $url 内容链接
     */
    public function pushMessage(int $type, string $patientId, string $locDesc, string $admDate, string $note, string $url)
    {

        $token = $this->getToken();
        if (!isset($token['access_token'])) {
            throw new FailedException("获取accessToken失败");
        }
        if ($token['remain_time'] <= 0) {
            throw new FailedException("accessToken已过期");
        }

        $signGenerator = new SignGenerator('md5', 'x5W2rlWkkJbPBkk8');
        $mcrypt = new AESDataMcrypt('aes-128-cbc', 'K2IbMQw8x4RbOgc6', '0102030405060708');
        $msgr = new GatewayManager($this->url, $this->appId, $token["access_token"], $signGenerator, $mcrypt);

        $class = config("dictionary.wx_push.type");

        $bizContent = [
            "requestXML" => "<Request>
                                <msgCode>$class[$type]</msgCode>
                                <patientId>$patientId</patientId>
                                <locDesc>$locDesc</locDesc>
                                <admDate>$admDate</admDate>
                                <note>$note</note>
                                <url>$url</url>
                              </Request>"
        ];
        list($code, $duration, $headers, $body) = $msgr->post('wechat.suifang.push', $bizContent, 'v1.0');

        $data = json_decode($body, true)['data'] ?? "";
        // 解密
        if ($data) {
            echo PHP_EOL . PHP_EOL;
            $data = $mcrypt->decrypt($data);
            $parseData = json_decode($data, true);
            if (json_last_error()) {
                $ret = $data;
            } else {
                $ret = json_encode($parseData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            }
            Log::write("微信推送返回：" . $ret, 'info');
        }
        return json_decode($body, true)['data'] ?? "";
    }
}
